<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>订单管理</el-breadcrumb-item>
      <el-breadcrumb-item>订单列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getOrderList">
            <el-button slot="append" icon="el-icon-search" @click="getOrderList"></el-button>
          </el-input>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="orderList" style="width: 100%" border stripe >
        <el-table-column type="index" label="#" align="center"></el-table-column>
        <el-table-column prop="order_number" label="订单编号" align="center"></el-table-column>
        <el-table-column prop="order_price" label="订单价格" width="90" align="center"></el-table-column>
        <el-table-column label="是否付款" width="90" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.is_pay">已付款</el-tag>
            <el-tag type="danger" v-else>未付款</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否发货" width="80" align="center">
					<template slot-scope="scope">
					  <el-switch v-model="scope.row.is_send" @change="userStateChanged(scope.row)" :disabled="scope.row.is_send">
					  </el-switch>
					</template>
				</el-table-column>
        <el-table-column prop="send_address" label="发件地址" align="center"></el-table-column>
        <el-table-column prop="receiving_address" label="收件地址" align="center"></el-table-column>
        <el-table-column label="下单时间" width="180" align="center">
          <template slot-scope="scope">
            {{ scope.row.order_time | dataFormat }}
          </template>
        </el-table-column>
				<el-table-column label="订单状态" width="100" align="center">
				  <template slot-scope="scope">
						<el-tag  :type="order_state[scope.row.state].type" effect="plain"> {{ order_state[scope.row.state].label }}</el-tag>
				  </template>
				</el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showBox(scope.row._id)"></el-button>
            <!-- <el-button type="success" icon="el-icon-location" size="mini" @click="showProgressBox"></el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
        :page-sizes="[10, 15, 20, 25]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 修改对话框 -->
    <el-dialog title="修改地址" :visible.sync="addresVisible" width="50%" @close="addressDialogClosed">
      <el-form :model="addressForm" :rules="addressFormRules" ref="addressFormRef" label-width="100px">
        <el-form-item label="省市区/县" prop="address1">
          <el-cascader ref="cascader" v-model="addressForm.address1" :options="cityData" :props="addressProps" clearable @change="hideCascader"></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address2">
          <el-input v-model="addressForm.address2"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addresVisible = false">取 消</el-button>
        <el-button type="primary" @click="editOrder">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 展示物流进度的对话框 -->
    <el-dialog title="物流进度" :visible.sync="progressVisible" width="50%">
      <el-timeline>
        <el-timeline-item v-for="(activity, index) in progressInfo" :key="index" :timestamp="activity.time">
            {{ activity.context }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import cityData from './citydata.js'
export default {
  data () {
    return {
			// 0 待付款，1 待发货 2 待收货 3 待评价 4已评价
			order_state:[ 
				{ type: '', label: '待付款' },
        { type: 'success', label: '待发货' },
        { type: 'info', label: '待收货' },
        { type: 'danger', label: '待评价' },
        { type: 'warning', label: '已评价' },
			],
      // 获取订单列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10,
				_id: ''
      },
      orderList: [],
      total: 0,
      // 控制修改对话框的显示与隐藏
      addresVisible: false,
      // 修改地址表单
      addressForm: {
        address1: [],
        address2: ''
      },
      // 修改表单的验证规则对象
      addressFormRules: {
        address1: [
          { required: true, message: '请选择省市区县', trigger: 'blur' }
        ],
        address2: [
          { required: true, message: '请填写详细地址', trigger: 'blur' }
        ]
      },
      cityData: cityData,
      // 指定级联选择器的配置对象
      addressProps: {
        expandTrigger: true,
        checkStrictly: true
      },
      // 控制物流进度对话框的显示与隐藏
      progressVisible: false,
      // 物流进度信息数据
      progressInfo: []
    }
  },
  created () {
    // 获取所有的订单列表
		this.queryInfo._id = JSON.parse(window.sessionStorage.getItem('userinfo'))._id;
    this.getOrderList()
  },
  methods: {
    async getOrderList () {
      console.log(this.queryInfo)
      const { data: res } = await this.$http.get('orders', { params: this.queryInfo })
      if (res.code !== 200) {
        return this.$message.error(res.msg)
      }
      this.orderList = res.data.data;
			this.orderList.forEach(item=>{
				item.receiving_address[0] = item.receiving_address[0].split(',');
			})
      this.total = res.data.total;
      this.$message.success(res.msg)
      console.log(this.orderList)
    },
    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      // console.log('pagesize:' + newSize)
      this.queryInfo.pagesize = newSize
      this.getOrderList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      // console.log('pagenum:' + newPage)
      this.queryInfo.pagenum = newPage
      this.getOrderList()
    },
    // 展示修改地址的对话框
    async showBox (id) {
			let address = [];
			const { data: res } = await this.$http.get('orders/' + id)
			console.log(res);
			if (res.code !== 200) return this.$message.error(res.msg)
			this.addressForm.order = res.data;
			let index_one = this.addressForm.order.receiving_address[0].indexOf('省');
			index_one != -1 && (address.push(this.addressForm.order.receiving_address[0].substring(0,index_one+1)))
			let index_two = this.addressForm.order.receiving_address[0].indexOf('市');
			index_two != -1 && (address.push(this.addressForm.order.receiving_address[0].substring(index_one + 1,index_two+1)))
			let index_three = this.addressForm.order.receiving_address[0].indexOf('区');
			let index_four = this.addressForm.order.receiving_address[0].indexOf('县');
			if (index_three!=-1) {
				address.push(this.addressForm.order.receiving_address[0].substring(index_two + 1,index_three+1))
			} else if (index_four!=-1) {
				address.push(this.addressForm.order.receiving_address[0].substring(index_two + 1,index_four+1))
			}
			this.addressForm.address1 = address;
			this.addressForm.address2 = this.addressForm.order.receiving_address[1];
      this.addresVisible = true
    },
    // 修改对话框的关闭事件
    addressDialogClosed () {
      this.$refs.addressFormRef.resetFields()
      this.addressForm = {}
    },
    hideCascader () {
      this.$refs.cascader.dropDownVisible = false;
			console.log(this.addressForm.address1);
    },
    async showProgressBox () {
      const { data: res } = await this.$http.get('/kuaidi/1106975712662')
      if (res.meta.status !== 200) {
        this.$message.error('获取物流进度失败！')
      }
      this.progressInfo = res.data
      // this.$message.success('获取物流信息成功！')
      this.progressVisible = true
      console.log(this.progressInfo)
    },
		// 修改订单信息并提交
		async editOrder() {
			const { data: res } = await this.$http.put('orders/' + this.addressForm.order._id, {
				 receiving_address: [this.addressForm.address1.join(','),this.addressForm.address2]
			})
			console.log(res)
			if (res.code !== 200) {
			  return this.$message.error(res.msg)
			}
			// 关闭对话框
			this.addresVisible = false
			// 刷新数据列表
			this.getOrderList()
			// 提示修改成功
			this.$message.success(res.msg)
		},
		// 监听switch开关状态的改变 是否发货
		async userStateChanged (item) {
		  console.log(item)
		  const { data: res } = await this.$http.put('orders/sendOutGoods',{ _id:item._id, is_send: item.is_send })
			console.log('send',res);
		  if (res.code !== 200) return this.$message.error(res.msg)
		  this.$message.success(res.msg)
		},
  }
}
</script>

<style lang="less" scoped>
  .el-cascader {
    width: 100%;
  }
</style>
